import React, { Component } from 'react'
import { Breadcrumb } from 'antd'
import { withRouter } from 'react-router-dom'
import routeData from "./../menuConfig"
import { getURLArray } from '../utils/routePathUtils'
class myBreadCrumb extends Component {
    state = {
        breadCrumbArray: []
    }
    getBreadCrumbArray = () => {
        console.log('路由变化', this.props.history);
        const url = this.props.history.location.pathname
        let urlArray = getURLArray(url)
        // let urlArray = url.split('/').slice(1)
        // urlArray = urlArray.map((r, i) => '/' + urlArray.slice(0, i + 1).join('/'))
        // console.log(urlArray);
        const breadCrumbArray = (<Breadcrumb style={{ margin: '16px 0' }}>{this.findPath(routeData, urlArray, 1)}</Breadcrumb>)
        this.setState({ breadCrumbArray })
    }
    //递归匹配,sourceData为嵌套结构，matchData为平行结构,layer为开始匹配的层数
    findPath(sourceData, matchData, layer) {
        const matchRoute = sourceData.find(r => r.key == matchData[layer])
        if (matchRoute) {
            if (matchData[layer + 1] && matchRoute.children) {
                return (
                    <>
                        <Breadcrumb.Item>{matchRoute.title}</Breadcrumb.Item>
                        {this.findPath(matchRoute.children, matchData, layer + 1)}
                    </>
                )
            } else {
                return (
                    <>
                        <Breadcrumb.Item>{matchRoute.title}</Breadcrumb.Item>
                    </>
                )
            }
        } else {
            return null
        }


    }
    componentDidMount() {
        this.props.history.listen(() => this.getBreadCrumbArray())
    }
    render() {
        return (
            <>
                {this.state.breadCrumbArray}
            </>
        )
    }
}
export default withRouter(myBreadCrumb)
